<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录数: {{ total }}</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px">
        <el-table
          :data="list"
          border
          :default-sort="{prop: 'timeOfEntry', order: 'descending'}"
        >
          <el-table-column width="50" label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" width="100">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="width:100%"
              >
            </template>W
          </el-table-column>W
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(row.id)"
              >分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-size="size"
            :page-sizes="[2, 5, 10]"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </el-row>
      </el-card>
      <!-- 实现新增员工的弹层 -->
      <el-dialog v-if="showDialog" title="新增员工" :visible.sync="showDialog">
        <addEmployees @success="hSuccess" @close="showDialog = false" />
      </el-dialog>
      <!-- 分配权限弹层 -->
      <el-dialog title="分配角色" :visible.sync="AssingRoleDialog">
        <AssingRole
          v-if="AssingRoleDialog"
          :cur-id="curId"
          @success="AssingRoleDialog=false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssingRole from './assignRole.vue'
import { delEmployess, getEmployess } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import addEmployees from './empDialog.vue'
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

export default {
  components: {
    addEmployees,
    AssingRole
  },
  data() {
    return {
      list: [],
      page: 1,
      size: 20,
      total: 0,
      showDialog: false,
      AssingRoleDialog: false, // 分配角色
      curId: ''
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // 列表数据渲染
    async loadEmployees() {
      try {
        const res = await getEmployess({ page: this.page, size: this.size })
        // console.log(res)
        if (res.code !== 10000) return this.$message.err(res.message)
        this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
        // 保存数据
      } catch (err) {
        console.log(err)
      }
    },
    // 格式化数据的函数
    formatData(id) {
      // console.log(id)
      return hireType[id] || '未知'
    },
    // 分页条数
    handleSizeChange(val) {
      this.size = val
      this.loadEmployees()
    },
    // 分页当前页
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployees()
    },
    // 关闭弹层,重新渲染数据
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    // 删除员工
    hDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployess(id)
        if (res.code === 10000) {
          this.$message.success(res.message)
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadEmployees()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    transZhKeyToExcel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(enkey => mapInfo[enkey])
      const data = list.map(item => Object.values(item))
      return { tHeader, data }
    },
    // excel导出
    handleDownload() {
      import('@/vendor/Export2Excel').then(excel => {
        const { tHeader, data } = this.transZhKeyToExcel(this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    hAssignRole(id) {
      this.curId = id
      this.AssingRoleDialog = true
    }
  }
}
</script>
